<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'

import { ref } from 'vue'

//文章分类数组categorys，绑定在文章分类选择框中
const categorys = ref([
    {
        "id": 3,
        "categoryName": "美食",
        "categoryAlias": "my",
        "createTime": "2023-09-02 12:06:59",
        "updateTime": "2023-09-02 12:06:59"
    },
    {
        "id": 4,
        "categoryName": "娱乐",
        "categoryAlias": "yl",
        "createTime": "2023-09-02 12:08:16",
        "updateTime": "2023-09-02 12:08:16"
    },
    {
        "id": 5,
        "categoryName": "军事",
        "categoryAlias": "js",
        "createTime": "2023-09-02 12:08:33",
        "updateTime": "2023-09-02 12:08:33"
    }
])

//先获取所有文章分类列表，以更新文章分类选择框
import { articleCategoryListService , articleListService , articleAddService , articleUpdateService ,articleDeleteService, articleDetailService} from '@/api/article.js'

//获取所有文章分类列表，更新categorys列表
const articleCategoryList = async () => {
    let result = await articleCategoryListService();
    categorys.value = result.data;
}
//页面渲染时就调用，获取所有文章分类列表并渲染
articleCategoryList();


//用户搜索时选中的分类id
const categoryId = ref('')

//用户搜索时选中的发布状态
const state = ref('')

//文章列表数据模型，渲染主页面，与后台POJO类对应
const articles = ref([
    {
        "id": 5,
        "title": "陕西旅游攻略",
        "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
        "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
        "state": "草稿",
        "categoryId": 2,
        "createTime": "2023-09-03 11:55:30",
        "updateTime": "2023-09-03 11:55:30"
    },
    {
        "id": 5,
        "title": "陕西旅游攻略",
        "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
        "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
        "state": "草稿",
        "categoryId": 2,
        "createTime": "2023-09-03 11:55:30",
        "updateTime": "2023-09-03 11:55:30"
    },
    {
        "id": 5,
        "title": "陕西旅游攻略",
        "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
        "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
        "state": "草稿",
        "categoryId": 2,
        "createTime": "2023-09-03 11:55:30",
        "updateTime": "2023-09-03 11:55:30"
    },
])

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页展示多少条，用户可更改

//当每页条数发生了变化，调用此函数，更改vue中定义的pageSize，然后按照新的页码布局重新获取文章列表
const onSizeChange = (size) => {
    pageSize.value = size
    articleList()  //调用获取文章列表的方法
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    articleList()  //调用获取文章列表的方法
}

//初始化时，调用获取所有文章，这个时候，携带上分页的信息给后端，后端返回的是分页的数据，然后渲染到页面上 -->
const articleList = async () => {
    //组装参数，其中state和categoryId是用户可而已选择的参数，先判断用户有没有选择，没有选择就不传，有选择就传
    let searchparams = {
        categoryId: categoryId.value? categoryId.value: '',
        state: state.value ? state.value : '',
        pageNum: pageNum.value,
        pageSize: pageSize.value
    }
    let result = await articleListService(searchparams)
    articles.value = result.data.items;  //见后端返回的数据
    total.value = result.data.total;

    //获取一下分类名称，因为写后端的时候只返回了文章所属分类的id,在渲染的时候需要把分类名称也渲染出来:

    for (let i = 0; i < articles.value.length; i++) {
        let article = articles.value[i];
        for (let j = 0; j < categorys.value.length; j++) {
            if (article.categoryId == categorys.value[j].id) {
                article.categoryName = categorys.value[j].categoryName;
            }
        }
    }}
//页面渲染时就调用，获取所有文章列表并渲染
articleList();

//富文本编辑器
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
//抽屉
import { Plus } from '@element-plus/icons-vue'
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型，文章的详情信息articleModel，是一个对象
const articleModel = ref({
    title: '',
    categoryId: '',
    coverImg: '',  //文章封面图片的url
    content: '',
    state: ''
})

//elmessage
import { defaultInitialZIndex, ElMessage } from 'element-plus'


//上传图片需要使用token，从store里获取
import { useTokenStore } from '@/stores/token.js'
//调用这个函数获取一个store实例，实例.token就是token的值
const tokenStore = useTokenStore()

//上传图片成功的回调函数，返回的是图片的在阿里云上的url
const uploadSuccess = (result) => {
    articleModel.value.coverImg = result.data;  //后台返回的json中的data字段就是图片的url
    console.log(result.data);
}

//调用添加文章的方法，接受一下触发按钮时传入的参数，根据不同按钮传入不同的参数，赋值给articleModel.value.state，然后调用添加文章的方法，传入文章的详情信息articleModel，由表单获取
const addArticle = async (articlestate) => {
    //组装参数
    articleModel.value.state = articlestate;
    //调用添加文章的方法，传入文章的详情信息articleModel，由表单获取
    let result = await articleAddService(articleModel.value)
        ElMessage.success(result.data)
        //添加成功，关闭抽屉
        visibleDrawer.value = false
        //重新获取文章列表
        articleList()
    }


//扩展：抽屉的标题
const drawerTitle = ref('')
//扩展：暂存文章id
const articleId = ref('')

//修改文章，复用同一个抽屉
const Editarticle = (row) => {
    //数据回写到新的抽屉中
    articleModel.value.title = row.title;
    articleModel.value.categoryId = row.categoryId;
    articleModel.value.coverImg = row.coverImg;
    articleModel.value.content = row.content;
    articleModel.value.state = row.state;
    //多传入一个当前文章的id
    articleId.value = row.id;
    //将抽屉显示出来
    visibleDrawer.value = true
    //将抽屉的标题改为编辑文章
    drawerTitle.value = '编辑文章'
}
//发出修改请求，关闭抽屉，重新获取文章列表
const updateArticle = async () => {
    //组装参数
    let params = {
        id: articleId.value,
        title: articleModel.value.title,
        categoryId: articleModel.value.categoryId,
        coverImg: articleModel.value.coverImg,
        content: articleModel.value.content,
        state: articleModel.value.state
    }
    //调用修改文章的方法
    let result = await articleUpdateService(params)
    //提示
    ElMessage.success(result.data)
    //修改成功，关闭抽屉
    visibleDrawer.value = false
    //重新获取文章列表
    articleList()
}

//删除文章，用确认提示框
import { ElMessageBox } from 'element-plus'
const Deletearticle = (row) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        //调用删除文章的方法
        let result = articleDeleteService(row.id);
        //提示
        ElMessage({
        type: 'success',
        message: '删除成功！后台说：' + result.data,
        })
        //删除成功，重新获取文章列表
        articleList()
    }).catch(() => {
        //取消删除
        ElMessage({
            type: 'info',
            message: '已取消删除'
        });
    });
}

//绑定一个参数控制文章详情弹窗的展示
const articleDetail = ref(false)
//数据模型接收文章详情用于展示，包括文章的标题，分类，封面，内容，发布状态，创建时间，更新时间
const articleDetailModel = ref({
    id: '',
    title: '',
    content: '',
    coverImg: '',
    state: '',
    categoryId: '',
    createUser: '',
    createTime: '',
    updateTime: ''
})
//点击每一行任意位置时触发的事件，发出请求文章详情（异步），控制渲染一个弹窗
const handleRowClick = async (row) => {
    //调用获取文章详情的方法，传入文章的id
    let result = await articleDetailService(row.id)
    //把后台返回的数据赋值给articleDetailModel
    articleDetailModel.value = result.data
    //控制渲染一个弹窗
    articleDetail.value = true
    //根据categoryId获取分类名
    for (let i = 0; i < categorys.value.length; i++) {
        if (articleDetailModel.value.categoryId == categorys.value[i].id) {
            articleDetailModel.value.categoryName = categorys.value[i].categoryName;
        }
    }
}

//关闭文章详情弹窗，同时清空一下数据模型
const closeArticleDetail = () => {
    articleDetail.value = false
    articleDetailModel.value = {
        id: '',
        title: '',
        content: '',
        coverImg: '',
        state: '',
        categoryId: '',
        createUser: '',
        createTime: '',
        updateTime: ''
    }

}





</script>


<template>
    <el-card class="page-container">
        <!-- 头 -->
        <template #header>
            <div class="header">
                <span>文章管理</span>
                <div class="extra">
                    <!-- visibleDrawer控制抽屉是否显示 -->
                    <el-button type="primary" @click="visibleDrawer = true; drawerTitle = '添加文章'">添加文章</el-button>
                </div>
            </div>
        </template>

        <!-- 搜索表单 文章分类的 el-select下拉选择框。el-option选项：
         v-model="categoryId"绑定用户选择的选项的id ，v-for="c in categorys  遍历渲染出列表categorys，c是别名，每一列表项对用一个选项  渲染时:label="c.categoryName"绑定一下-->
        <el-form inline>
            <el-form-item label="文章分类：">
                <el-select placeholder="请选择" v-model="categoryId" style="width:240px">
                    <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>
        <!-- 发布状态的下拉选择框。v-model="state"用户选择的发布状态的选项id -->
            <el-form-item label="发布状态：">
                <el-select placeholder="请选择" v-model="state" style="width: 220px;">
                    <el-option label="已发布" value="已发布"></el-option>
                    <el-option label="草稿" value="草稿"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <!-- 搜索按钮，可以选择搜索也可以全部搜索 ，调用articleList方法重新查询一下文章-->
                <el-button type="primary" @click="articleList">搜索</el-button>
                <!-- 重置按钮，事件可以直接写在标签中 -->
                <el-button @click="categoryId = ''; state = ''">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 文章列表 想在点击每一行任意位置时能触发一个事件-->
        <el-table :data="articles" style="width: 100%" @row-click="handleRowClick">
            <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
            <!-- 渲染列表时绑定一下由id值转化的分类名 -->
            <el-table-column label="分类" prop="categoryName"></el-table-column>
            <el-table-column label="发表时间" prop="createTime"> </el-table-column>
            <el-table-column label="状态" prop="state"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <!-- 编辑按钮，绑定编辑方法，携带row进入方法，方法负责组装查询参数和渲染抽屉 -->
                    <el-button :icon="Edit" circle plain type="primary" @click = Editarticle(row)></el-button>
                    <!-- 同理 -->
                    <el-button :icon="Delete" circle plain type="danger" @click = Deletearticle(row)></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>

        <!-- 分页条 @size-change分页条标签的事件，每页展示多少条的输入框改变后触发  @current-change切换页码时触发-->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />


        <!-- 弹窗显示文章详情,绑定一个参数控制显示，仅仅展示信息和图片，同时定义点好看的布局，样式 -->
        <el-dialog title="文章详情" :visible.sync="visibleDialog" width="80%" v-model="articleDetail">                        
            <div class="article-detail">
                <h1>文章标题：</h1>
                <div class="title">{{ articleDetailModel.title }}</div><br><br><br>
                <div class="info">
                    <span>分类：{{ articleDetailModel.categoryName }}</span>
                    <span>发表时间：{{ articleDetailModel.createTime }}</span>
                    <span>更新时间：{{ articleDetailModel.updateTime }}</span>
                </div><br><br><br><br>
                <div class="content">
                    
                    <img v-if="articleDetailModel.coverImg" :src="articleDetailModel.coverImg" alt="文章封面" class="cover-img" />
                    <h4>文章内容：</h4>
                    <div v-html="articleDetailModel.content"></div>
                </div>
            </div>
            <!-- 关闭按钮，绑定单击事件 -->
            <el-button type="primary" @click="closeArticleDetail()">关闭</el-button>
        </el-dialog>
        
        <!-- 抽屉组件v-model="visibleDrawer"  绑定一个数据参数控制是否显示 ,
        ！！！再绑定一个数据作为抽屉的标题drawerTitle，以复用抽屉-->
        <el-drawer v-model="visibleDrawer" :title="drawerTitle" direction="rtl" size="50%">
            <!-- 添加文章表单,绑定数据articleModel文章具体信息，一个对象 -->
            <el-form :model="articleModel" label-width="100px">
                <el-form-item label="文章标题">
                    <!-- v-model="articleModel.title"绑定了文章具体信息的title属性,双向绑定其他的值，发出请求 -->
                    <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="文章分类">
                    <!-- v-model="articleModel.categoryId"绑定了文章具体信息的categoryId属性,双向绑定其值，发出请求 -->
                    <el-select placeholder="请选择" v-model="articleModel.categoryId">
                        <!-- 选项框渲染，来自于查询所有文章分类 -->
                        <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="文章封面">

                    <!-- el-upload上传框，上传文章封面，并自动发出一个ajax请求，需要跨域，因此路径上加上/api被我的nginx代理了拦截 

                        auto-upload:设置是否自动上传
                        action:设置服务器接口路径
                        name:设置上传的文件字段名
                        :headers:设置上传的请求头，带上token，先从store里获取
                        :on-success:设置上传成功的回调函数
                     -->
                   
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                    action="/api/upload"
                    name="file"
                    :headers="{'Authorization':tokenStore.token}"
                    :on-success="uploadSuccess"
                    >

                            <!-- 绑定articleModel.coverImg，即上传的图片在阿里云上的url，若没有则不渲染 -->
                        <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>



                    </el-upload>
                </el-form-item>

                <el-form-item label="文章内容">
                    <div class="editor">
                        <!-- 富文本编辑器 ，即收集用户输入的文章内容：articleModel.content-->
                        <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html">
                        </quill-editor>
                    </div>
                </el-form-item>

                <!-- 加一个条件判断，如果当前抽屉的标题是添加文章，就渲染，如果不是，就不渲染 -->
                <el-form-item v-if = "drawerTitle === '添加文章'">
                    <!-- 细节，两个按钮绑定同样的方法，传入的参数不同，为请求参数肤质不同的值 -->
                    <el-button type="primary" @click="addArticle('已发布')">发布</el-button>
                    <el-button type="info" @click="addArticle('草稿')">草稿</el-button>
                </el-form-item>

                <!-- 若当前的抽屉的标题是编辑文章，则渲染一个提交修改的button -->
                <el-form-item v-if="drawerTitle==='编辑文章'">
                    <el-button type="primary" @click="updateArticle('已发布')">更改为已发布</el-button>
                    <el-button type="info" @click="updateArticle('草稿')">更改为草稿</el-button>
                </el-form-item>

            </el-form>
        </el-drawer>
    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}


给个好看的样式文字分大小，图片约束展示，不要占比太大
.article-detail {
    font-size: 16px;
    line-height: 1.5;
    margin: 20px;
    .title {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
    }

   .info {
        color: #888;
        margin-bottom: 10px;
    }

   .content {
        img {
            max-width: 100%;
            height: auto;
        }
    }
}

</style>